<template>
  <component
    is="a-modal"
    v-model:visible="visible"
    :width="1200"
    :title="title"
    :mask-closable="false"
    :ok-loading="loading"
    @cancel="close"
    @before-ok="submit">
    <!-- 表单信息 start -->
    <a-form ref="formRef" :model="formData" :rules="rules" :auto-label-width="true">
      <a-form-item label="排名" field="sort_order">
        <a-input v-model="formData.sort_order" placeholder="请输入排名" />
      </a-form-item>
      <a-form-item label="政策标题" field="policy_title">
        <a-input v-model="formData.policy_title" placeholder="请输入政策标题" />
      </a-form-item>
	  <a-form-item label="行政级别" field="policy_module">
	    <a-select
	        v-model="formData.xz_level"
	        :options="xzLevelData"
	        allow-clear
	        placeholder="请选择行政级别" />
	  </a-form-item>
      <a-form-item label="政策所属省" field="province_id" v-if="false">
        <a-select
          v-model="formData.province_id"
          :options="provinceOptions"
          allow-clear
          placeholder="请选择政策所属省"
          @change="handleProvinceChange"
        />
      </a-form-item>
      <a-form-item label="政策所属市" field="city_id" v-if="false">
        <a-select
          v-model="formData.city_id"
          :options="cityOptions"
          allow-clear
          placeholder="请选择政策所属市"
          :disabled="!formData.province_id"
          @change="handleCityChange"
        />
      </a-form-item>
      <a-form-item label="政策所属区" field="district_id" v-if="false">
        <a-select
          v-model="formData.district_id"
          :options="districtOptions"
          allow-clear
          placeholder="请选择政策所属区"
          :disabled="!formData.city_id"
        />
      </a-form-item>
     <div v-for="(item, index) in treeData" :key="index">
             <a-form-item :label="item.label" :field="`industry_category[${item.value}]`">
               <a-select
                 v-model="formData.industry_category[item.value]"
                 :options="item.children"
                 allow-clear
                 placeholder="请选择产业类别"
                 multiple
                 :max-tag-count="3"
                 :max-tag-placeholder="(omittedValues) => `+${omittedValues.length} 项`"
                 :max="10"
                 @change="handleSelectChange(formData.industry_category[item.value], item.value)"
               />
             </a-form-item>
           </div>
     
      <a-form-item label="申报日期" field="application_time_range">
        <a-range-picker v-model="formData.application_time_range"  mode="date"  />
      </a-form-item>
     <!-- <a-form-item label="申报结束时间" field="application_end_time">
        <a-date-picker v-model="formData.application_end_time" :show-time="true" mode="date" placeholder="请选择申报结束时间" />
      </a-form-item> -->
      <a-form-item label="是否展示" field="is_display">
        <sa-switch v-model="formData.is_display" checkedText="是"  uncheckedText="否"/>
      </a-form-item>
      <a-form-item label="来源" field="source">
        <a-input v-model="formData.source" placeholder="请输入来源" />
      </a-form-item>
      <a-form-item label="申请条件及材料" field="application_conditions">
        <ma-wangEditor v-model="formData.application_conditions" :height="400" />
      </a-form-item>
    </a-form>
    <!-- 表单信息 end -->
  </component>
</template>

<script setup>
import { ref, reactive, computed,watch } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import api from '../api/matching'
import commonApi from '@/api/common'

const emit = defineEmits(['success'])
// 引用定义
const visible = ref(false)
const loading = ref(false)
const formRef = ref()
const mode = ref('')
const provinceOptions = ref([])
const cityOptions = ref([])
const districtOptions = ref([])
const xzLevelData = ref([])
const treeData = ref([])
let title = computed(() => {
  return '政策匹配' + (mode.value == 'add' ? '-新增' : '-编辑')
})

// 表单信息
const formData = reactive({
  matching_id: null,
  lang_code: '',
  sort_order: null,
  policy_title: '',
  province_id: 0,
  city_id: 0,
  district_id: 0,
  project_category: '',
  industry_category:{},
  application_time_range: [], 
  application_start_time: null,
  application_end_time: null,
  is_display: null,
  source: '',
  xz_level: '',
  application_conditions: '',
})

// 验证规则
const baseRules = {
  lang_code: [{ required: true, message: '语言代码，如zh-CN、en-US等必需填写' }],
  policy_title: [{ required: true, message: '政策标题必需填写' }],
  province_id: [{ required: true, message: '政策所属省必需填写' }],
}

// 动态验证规则
const rules = reactive({ ...baseRules })

// 生成产业类别验证规则
const generateIndustryCategoryRules = () => {
  treeData.value.forEach(item => {
    if (item.is_required === 1) {
      // 当 is_required 为 1 时添加验证规则
      rules[`industry_category[${item.value}]`] = [
        { required: true, message: `${item.label} 必需选择`, trigger: 'change' }
      ]
    } else {
      // 当 is_required 不为 1 时移除验证规则
      delete rules[`industry_category[${item.value}]`]
    }
  })
}
const handleSelectChange = (value, key) => {
  // Add null checks
  if (value && Array.isArray(value) && value.length > 10) {
    formData.industry_category[key] = value.slice(0, 10);
    Message.warning('最多只能选择 10 个选项');
  }
}
// 监听 treeData 变化，更新验证规则
watch(treeData, generateIndustryCategoryRules, { immediate: true })

// 打开弹框
const open = async (type = 'add') => {
  mode.value = type
  visible.value = true
  formRef.value.resetFields()
  await initPage()
  // 初始化省数据
 
}

// 初始化页面数据
const initPage = async () => {
  const res = await commonApi.commonGet('/matchingRule/MatchingRule/index',{tree:true})
  treeData.value = res.data
  const xzLevel = await commonApi.commonGet('/cassification/ClassificationDictionary/getCate', {
    classification_type: 20
  })
  xzLevelData.value = xzLevel.data
  
}

// 加载省份数据
const loadProvinces = async () => {
  const resp = await commonApi.commonGet('/Cnarea/Cnarea/getSelect',{level:1}) // 替换为实际获取省份的 API 地址
  provinceOptions.value = resp.data.map(item => ({
    value: item.value,
    label: item.label
  }))
}

// 加载城市数据
const loadCities = async (provinceId) => {
  const resp = await commonApi.commonGet('/Cnarea/Cnarea/getSelect', {level:2,parent_code:provinceId }) // 替换为实际获取城市的 API 地址
  cityOptions.value = resp.data.map(item => ({
   value: item.value,
   label: item.label
  }))
  // 清空市选择后，同时清空区选择
	  formData.city_id = 0
	  formData.district_id = 0
	  // districtOptions.value =
}

// 加载区县数据
const loadDistricts = async (cityId) => {
  const resp = await commonApi.commonGet('/Cnarea/Cnarea/getSelect', { level:3,parent_code:cityId }) // 替换为实际获取区县的 API 地址
  districtOptions.value = resp.data.map(item => ({
   value: item.value,
   label: item.label
  }))
   formData.district_id = 0
}

// 省选择变化处理
const handleProvinceChange = async (provinceId) => {
  if (provinceId) {
    await loadCities(provinceId)
  } else {
	
    formData.city_id = 0
    // districtOptions.value = []
    formData.district_id = 0
  }
}

// 市选择变化处理
const handleCityChange = async (cityId) => {
  if (cityId) {
    await loadDistricts(cityId)
  } else {
	  if(cityId){
		  // districtOptions.value = []
		  formData.district_id = 0
	  }
   
  }
}

// 设置数据
const setFormData = async (data) => {
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
      formData[key] = data[key]
    }
  }
  await loadProvinces() 
  // 若有省市区数据，重新加载对应数据
  if (data.province_id!=='') {
    await loadCities(data.province_id)
    if (data.city_id!=='') {
      await loadDistricts(data.city_id)
    }
  }
  formData.application_time_range=[formData.application_start_time,formData.application_end_time]
}

// 数据保存
const submit = async (done) => {
  // const validate = await formRef.value?.validate()
  // console.log(await formRef.value.Handler)
  // if (validate) {
    loading.value = true
	
	
    let data = { ...formData }
	
    let result = {}
	if(data.city_id=='') data.city_id=0
	if(data.district_id=='') data.city_id=0
	  const [application_start_time, application_end_time] = formData.application_time_range;
	const submitData = formData;
	submitData.application_start_time=application_start_time
	submitData.application_end_time=application_end_time
		// console.log(submitData)
    // delete submitData.application_time_range;
			  
    if (mode.value === 'add') {
      // 添加数据
      submitData.matching_id = undefined
      result = await api.save(submitData)
    } else {
      // 修改数据
      result = await api.update(submitData.matching_id, submitData)
    }
    if (result.code === 200) {
      Message.success('操作成功')
      emit('success')
      done(true)
    }
    // 防止连续点击提交
    setTimeout(() => {
      loading.value = false
    }, 500)
  // } else {
  //   done(false)
  // }
}

// 关闭弹窗
const close = () => (visible.value = false)

defineExpose({ open, setFormData })
</script>